<?php
/*
	本插件：$this->model('api')->方法名();
	其他地方调用：model('jy_aiagent/api')->方法名();
*/
namespace jy_aiagent;
defined('BY_JYA') or exit('error');
class api extends \plugin{
	public function __construct(){
		$setting=plugin('jy_aiagent')->plugin_setting('basic');
		$this->setting=$setting;
		if(!$this->setting['apikey']){
			return '';
		}
		if($this->setting['expire']<TIMESTAMP || !$this->setting['access_token']){
			$this->getAccessToken();
		}
	}
	//发起http请求
	public function request($api,$post='',$isres=false){
		if(!$this->setting['apikey']){
			if($isres){
				$res='AI暂时无法使用，请联系管理员，设置好基本参数API密钥';
				return $res;
			}else{
				exi('AI暂时无法使用，请联系管理员，设置好基本参数API密钥','error');
			}
		}
		$post=$post?ijson_encode($post):'';
		$extra=array(
			'Content-Type' => 'application/json',
			'Authorization'=> ' Bearer '.$this->setting['access_token']
		);
		$rurl='https://xiaozhi.me'.$api;
		//print_r($rurl);exit;
		$result=cfc('http')->ihttp_request($rurl,$post,$extra);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($isres){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		//file_put_contents(ROOT_D.'/1.txt',$data);
		$data=@json_decode($data,true);
		if(!is_array($data) || !$data){
			$message='访问接口错误，以下为原始数据：'.$result['content'];
			if($isres){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	public function getAccessToken($continue=false,$noexi=0){//获取access_token
		$noexi=$noexi?:$_SESSION['noexi'];
		if($this->setting['expire']>TIMESTAMP && !$continue && $this->setting['access_token']){
			return $this->setting['access_token'];
		}
		if(!$this->setting['apikey']){
			return false;
		}else{
			$url = "https://xiaozhi.me/api/developers/token";
		}	
		$post=array(
			'secret_key'=>$this->setting['apikey'],
		);
		$content = cfc('http')->ihttp_request($url,$post);
		if(is_error($content) && !$noexi){
			exi('获取token失败, 请稍后重试！错误详情：'.$content['message'],'error');
		}
		$token = @json_decode($content['content'], true);
		if(empty($token['data']) || empty($token['data']['token']) && !$noexi) {
			exi('获取token失败, 请稍后重试！错误代码-' . $token['errcode'] . '，错误信息-' . $token['errmsg'],'error');
		}
		$this->setting['access_token'] = $token['data']['token'];
		$this->setting['expire'] = TIMESTAMP + 24*3600 - 200;
		$this->plugin_setting('basic',$this->setting);
		return $token['access_token'];
	}
	//获取音色列表
	public function gettts($isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/user/tts-list');
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('获取音色失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return '获取音色失败：'.$res['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		$list=array();
		foreach($data['tts_voices'] as $lng=>$vlist){
			foreach($vlist as $item){
				$list[]=$item;
			}
		}
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($data['tts_voices']));
		return $list;
	}
	//获取智能体模板
	public function getagentstpl($post=array(),$isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/developers/agent-templates');
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($res['data']));
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('获取智能体失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return '获取智能体失败：'.$res['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
	//编辑智能体模板
	public function upagentstpl($params=array(),$isexi=false) {
		$isres=$isexi?false:true;
		$post=array(
			'agent_name'=>trim($params['title']),
			'character'=>trim($params['desc']),
			'tts_voices'=>json_decode($params['tts_voices'],true),
			'default_tts_voice'=>trim($params['default_tts_voice']),
			'llm_model'=>trim($params['llm_model']),
			'assistant_name'=>trim($params['ainame']),
			'user_name'=>trim($params['user_name']),
			'tts_speech_speed'=>trim($params['tts_speech_speed']),
			'asr_speed'=>trim($params['asr_speed']),
			'tts_pitch'=>trim($params['tts_pitch']),
			'tts_voice_name'=>trim($params['tts_voice_name']),
		);
		$params['apiid']=0;
		if($params['apiid']){
			$res=$this->request('/api/developers/agent-templates-config/'.$params['apiid'],$post);
		}else{
			$res=$this->request('/api/developers/agent-templates-config',$post);
		}
		//file_put_contents(ROOT_D.'/2.txt',ijson_encode($res['data']));
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('编辑智能体失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return '编辑智能体失败：'.$res['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
	//删除智能体模板
	public function delagentstpl($apiid,$isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/developers/agent-templates/'.$apiid);
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($res['data']));
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('删除智能体模板失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return '删除智能体模板失败：'.$res['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
	//获取智能体列表
	public function getagents($post=array(),$isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/agents');
		print_r($res);exit;
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('获取智能体失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return '获取智能体失败：'.$res['code'].','.$res['message'];
			}
		}
		print_r($res);exit;
		$data=$res['data'];
		return $data;
	}
	//删除智能体
	public function deluseragent($agentapiid=0,$isexi=false) {
		if(!$agentapiid){
			return '';
		}
		$post=array(
			'id'=>$agentapiid,
		);
		$res=$this->request('/api/agents/delete',$post);
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('更新智能体失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return '更新智能体失败：'.$res['error']['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
	//创建客户智能体
	public function adduseragents($agent,$agentid=0,$isexi=false) {
		$post=array(
			'agent_name'=>'[API]['.$agent['id'].']:'.trim($agent['title']),
			'assistant_name'=>trim($agent['ainame']),
			'character'=>trim($agent['desc']),
			'tts_voice'=>trim($agent['tts_voice']),
			'llm_model'=>trim($agent['llm_model']),
			'language'=>trim($agent['language']),
		);
		$post['llm_model']=$post['llm_model']=='doubao'?'doubao-pro':$post['llm_model'];
		$post['llm_model']=$post['llm_model']=='kimi'?'kimi-k2':$post['llm_model'];
		$post['llm_model']=$post['llm_model']=='qwen3'?'qwen':$post['llm_model'];
		if($agent['apiid']){
			$res=$this->request('/api/agents/'.$agent['apiid'].'/config',$post);
		}else{
			$res=$this->request('/api/agents',$post);
		}
		if($res['message']=='智能体不存在'){
			$res=$this->request('/api/agents',$post);
		}
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('更新智能体失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		if($agentid && $data['id']){
			pdo_update('jy_aiagent_useragent',array('apiid'=>trim($data['id'])),array('id'=>$agentid,'uniacid'=>$_SESSION['uniacid']));
		}
		return $data;
	}
	//设备列表
	public function getdevices($agentid,$isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/agents/'.$agentid.'/devices');
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('设备列表失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//获取设备信息
	public function getdevicesitem($agentid,$mac,$isexi=false) {
		$isres=$isexi?false:true;
		$res=$this->request('/api/agents/'.$agentid.'/devices/'.$mac);
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('设备列表失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//绑定设备
	public function addusergoods($params,$agentapiid=0,$isexi=false) {
		$post=array(
			'verificationCode'=>$params['code'],
		);
		if($agentapiid){
			$res=$this->request('/api/agents/'.$agentapiid.'/devices',$post);
		}else{
			$res=$this->request('/api/agents/devices',$post);
		}
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('绑定设备失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//删除设备
	public function delusergoods($params,$isexi=false) {
		if(!$params['agentapiid'] || !$params['deviceid']){
			exi('删除设备失败：设备ID异常！','error');
			return false;
		}
		$post=array(
			'deviceId'=>$params['deviceid'],
		);
		$res=$this->request('/api/agents/'.$params['agentapiid'].'/devices/delete',$post);
		$isexi=1;
		if(!$res['success']){
			if($isexi){
				exi('删除设备失败：'.$res['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//对话列表
	public function getchat($agentid,$isexi=false) {
		$isres=$isexi?false:true;
		if(!$agentid){
			if($isexi){
				exi('获取对话列表失败：智能体APIID不存在！','error');
			}else{
				return false;
			}
		}
		$res=$this->request('/api/agents/'.$agentid.'/chats');
		if(!$res['success']){
			if($isexi){
				exi('获取对话列表失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//对话列表详情
	public function getchatitem($agentid,$chatid=0,$isexi=false) {
		$isres=$isexi?false:true;
		if(!$agentid || !$chatid){
			if($isexi){
				exi('获取对话列表详情失败：对话ID不存在！','error');
			}else{
				return false;
			}
		}
		$res=$this->request('/api/agents/'.$agentid.'/chats/'.$chatid.'/messages');
		if(!$res['success']){
			if($isexi){
				exi('获取对话列表详情失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//删除对话
	public function delchat($agentlog=array(),$isexi=false) {
		if(!$agentlog['agentapiid'] || !$agentlog['chatapiid']){
			return '';
		}
		$res=$this->request('/api/agents/'.$agentlog['agentapiid'].'/chats/'.$agentlog['chatapiid']);
		if(!$res['success']){
			$isexi=1;
			if($isexi){
				exi('更新对话失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return '更新对话失败：'.$res['error']['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
	//获取向量
	public function getembedding($agentid,$isexi=false) {
		$isres=$isexi?false:true;
		if(!$agentid){
			if($isexi){
				exi('获取向量失败：智能体APIID不存在！','error');
			}else{
				return false;
			}
		}
		$res=$this->request('/api/agents/'.$agentid.'/available-embeddings');
		if(!$res['success']){
			if($isexi){
				exi('获取向量失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//添加声纹
	public function addshengwen($postdata,$agentid=0,$isexi=false) {
		$isres=$isexi?false:true;
		if(!$agentid){
			if($isexi){
				exi('添加声纹失败：智能体不存在！','error');
			}else{
				return false;
			}
		}
		$post=array(
			'name'=>$postdata['title'],
			'description'=>$postdata['desc'],
			'embedding'=>json_decode($postdata['embedding'],true),
		);
		$res=$this->request('/api/agents/'.$agentid.'/speakers',$post);
		if(!$res['success']){
			if($isexi){
				exi('添加声纹失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//编辑声纹
	public function editshengwen($postdata,$agentid=0,$isexi=false,$apiid=0) {
		$isres=$isexi?false:true;
		if(!$agentid || !$apiid){
			if($isexi){
				exi('编辑声纹失败：智能体/声纹不存在！','error');
			}else{
				return false;
			}
		}
		$post=array(
			'name'=>$postdata['title'],
			'description'=>$postdata['desc'],
		);
		if($postdata['embedding']){
			$post['embedding']=json_decode($postdata['embedding'],true);
		}
		//print_r($post);exit;
		$res=$this->request('/api/agents/'.$agentid.'/speakers/'.$apiid,$post);
		if(!$res['success']){
			if($isexi){
				exi('编辑声纹失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return false;
			}
		}
		$data=$res['data'];
		return $data;
	}
	//删除声纹
	public function delshengwen($shengwenlog=array(),$isexi=false) {
		if(!$shengwenlog['agentapiid'] || !$shengwenlog['apiid']){
			return false;
		}
		//print_r('/api/agents/'.$shengwenlog['agentapiid'].'/speakers/'.$shengwenlog['apiid']);exit;
		$res=$this->request('/api/agents/'.$shengwenlog['agentapiid'].'/speakers/'.$shengwenlog['apiid']);
		if(!$res['success']){
			if($isexi){
				exi('删除声纹失败：'.$res['error']['code'].','.$res['message'],'error');
			}else{
				return '删除声纹失败：'.$res['error']['code'].','.$res['message'];
			}
		}
		$data=$res['data'];
		return $data;
	}
}
?>